package com.loren.demo14.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.loren.demo14.dto.UserAuthDto;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@AllArgsConstructor
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    /**
     * 定义请求头的key
     */
    private static final String TOKEN_HEADER = "Authorization";

    private final ObjectMapper objectMapper;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取token
        String token = request.getHeader(TOKEN_HEADER);
        if (StringUtils.isNotBlank(token)) {
            String tokenValue = this.stringRedisTemplate.opsForValue().get(token);
            if (StringUtils.isNotBlank(tokenValue)) {
                // 从redis中获取用户信息（在登录成功处理器那保存的）
                UserAuthDto userAuth = this.objectMapper.readValue(tokenValue, UserAuthDto.class);
                // 构建认证信息
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userAuth, null, userAuth.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将认证信息设置到Spring Security的上下文中，从而让Spring Security知道该请求已经认证过了
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        // 执行下面的过滤器
        filterChain.doFilter(request, response);
    }
}